package se

import (
	"regexp"
	"strings"
	"unicode"

	"gitee.com/xuender/oils/sets"
)

// Split 分词.
func Split(txt string) sets.Strings {
	re := regexp.MustCompile(`\w+|\p{Han}`)

	return SplitWord(re.FindAllString(txt, -1))
}

// SplitWord 拆分词,如: IsWord 拆分 is, word.
func SplitWord(elems []string) sets.Strings {
	ret := sets.NewStrings()
	for _, e := range elems {
		split(ret, e)
	}

	return ret
}

func split(set sets.Strings, e string) {
	start := 0
	rs := []rune(e)
	isUpper := false

	for i, r := range rs {
		if r == '_' {
			_ = addString(rs, start, i, set)
			start = i + 1

			continue
		}

		if unicode.IsUpper(r) {
			if !isUpper && addString(rs, start, i, set) {
				start = i
			}
		} else if isUpper && addString(rs, start, i-1, set) {
			start = i - 1
		}

		isUpper = unicode.IsUpper(r)

		if unicode.IsNumber(r) {
			_ = addString(rs, start, i, set)
			start = i + 1

			set.Add(string([]rune{r}))
		}
	}

	_ = addString(rs, start, len(rs), set)
}

func addString(rs []rune, start, end int, set sets.Strings) bool {
	if start < end {
		set.Add(strings.ToLower(string(rs[start:end])))

		return true
	}

	return false
}

// IsWord 是否是字.
func IsWord(r rune) bool {
	return unicode.Is(unicode.Scripts["Han"], r) ||
		unicode.IsNumber(r) ||
		unicode.IsLetter(r)
}
